package com.webserver.servlet;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.io.RandomAccessFile;

public class LoginServlet extends HttpServlet {
    public void service(HttpRequest request, HttpResponse response){
        String username = request.getParameters("username");
        String password = request.getParameters("password");

        if (username==null||password==null){
            File file = new File("./webapps/myweb/login_info_error.html");
            response.setEntity(file);
            return;
        }

        try(RandomAccessFile raf = new RandomAccessFile("./user.dat","rw");){
            for (int i = 0;i<raf.length()/100;i++){
                raf.seek(i*100);
                byte[]data = new byte[32];
                raf.read(data);
                String name = new String(data,"utf-8").trim();
                if (name.equals(username)){
                    raf.read(data);
                    String pwd = new String(data,"utf-8").trim();
                    if (pwd.equals(password)){
                        File file = new File("./webapps/myBlog/index.html");
                        response.setEntity(file);
                        return;
                    }
                    break;
                }
            }
            File file = new File("./webapps/myweb/login_fail.html");
            response.setEntity(file);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
